package com.kingtone.rongji.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.kingtone.rongji.R;
import com.kingtone.rongji.biz.ProductCategory;
import com.kingtone.rongji.tool.AppRestClient;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CategoryLeftAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private List<ProductCategory> mData;
	
	private DisplayImageOptions mOptions;
	
	public CategoryLeftAdapter(Context context) {
		mData = new ArrayList<ProductCategory>();
		mInflater = LayoutInflater.from(context);
		
		mOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565).delayBeforeLoading(100).build();
	}
	
	public void append(List<ProductCategory> data) {
		mData.addAll(data);
		notifyDataSetChanged();
	}
	
	public void addAll(List<ProductCategory> data) {
		mData.clear();
		mData.addAll(data);
		notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return mData.size();
	}

	@Override
	public Object getItem(int arg0) {
		return mData.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(int arg0, View view, ViewGroup arg2) {
		ViewHolder holder;
		if (view == null) {
			view = mInflater.inflate(R.layout.left_category_item, null);
			holder = new ViewHolder();
			holder.initView(view);
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		
		// Data
		ProductCategory item = mData.get(arg0);
		if(null != item) {
			//holder.imageView.setImageResource(ProductCategory.getImageByCatrgoryId(item.getCategoryId()));
			ImageLoader.getInstance().displayImage(AppRestClient.BASE_CATEGORY2_URL + item.getCategoryId() + ".jpg", holder.imageView, mOptions);
		}
		
		return view;
	}
	
    private static class ViewHolder {
        ImageView imageView;
        
        void initView(View view) {
        	imageView = (ImageView) view.findViewById(R.id.image);
        }
    }

}
